package manager

import (
	"errors"
	"fmt"
	"github.com/chai2010/winsvc"
	"github.com/wonderivan/logger"
	"os/exec"
	"strings"
)

//ServiceManager 服务启停管理
type ServiceManager struct {
	ServiceName string
	ServiceDis  string
}

//Init 初始化
func (_this *ServiceManager) Init() {}

//IsServiceRunning 判断服务是否运行中（STOPPED为不运行）
func (_this *ServiceManager) IsServiceRunning() bool {
	sta, _ := winsvc.QueryService(_this.ServiceName)
	return strings.ToUpper(strings.TrimSpace(sta)) != "STOPPED"
}

//ServiceStart 停止服务
func (_this *ServiceManager) ServiceStart() {
	if err := winsvc.StartService(_this.ServiceName); err != nil {
		logger.Alert("startService:", err)
	}
	fmt.Printf("Done\n")
}

//ServiceStop 停止服务
func (_this *ServiceManager) ServiceStop() {
	if err := winsvc.StopService(_this.ServiceName); err != nil {
		logger.Alert("stopService:", err)
	}
	fmt.Printf("Done\n")
	return
}

//ServiceRestart 重启服务
func (_this *ServiceManager) ServiceRestart() {
	_this.ServiceStop()
	_this.ServiceStart()
	return
}

//FindNameByDis 如果服务中有中文，目前会出错。此函数有问题，暂不使用
func (_this *ServiceManager) FindNameByDis() error {
	cmd := exec.Command("sc", "query")
	if buf, err := cmd.Output(); err == nil {
		serviceString := string(buf)
		println(serviceString)
		disBuf := strings.Split(serviceString, "\r")
		for i := 0; i < len(disBuf); i++ {
			if strings.Contains(disBuf[i], "SERVICE_NAME") && strings.Contains(disBuf[i+1], "DISPLAY_NAME") {
				disBuf[i] = strings.TrimSpace(strings.Trim(strings.Trim(disBuf[i], "\r"), "\n"))
				serviceName := strings.TrimSpace(strings.Trim(disBuf[i], "SERVICE_NAME:"))
				i++
				disBuf[i] = strings.TrimSpace(strings.Trim(strings.Trim(disBuf[i], "\r"), "\n"))
				disName := strings.TrimSpace(strings.Trim(disBuf[i], "DISPLAY_NAME:"))
				println(disName)
				if disName == _this.ServiceDis {
					_this.ServiceName = serviceName
					return nil
				}
			}
		}
		return errors.New("没有找到服务名称")
	}
	return errors.New("获取服务列表失败")
}

//func (_this *serviceManager) FindDisByName() {}
